<?php
namespace ctrl;

/**
 * 基类控制器
 * Class BaseCtrl
 * @package ctrl
 */
class BaseCtrl {

    protected $twig;
    protected $data = [];


    /**
     * BaseCtrl constructor.
     */
    public function __construct() {
        $loader = new \Twig\Loader\FilesystemLoader(TEMPDIR.'/template');
        $this->twig = new \Twig\Environment($loader, [
          //  'cache' => '/path/to/compilation_cache',
        ]);
    }

    /**
     * 插入变量
     * @param $var
     * @param null $value
     */
    protected function assign($var, $value=null) {
        if(is_array($var)) {
            $this->data = array_merge($this->data, $var);
        } else {
            $this->data[$var] = $value;
        }
    }

    /**
     * 渲染模板
     * @param $template
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    protected function display($template) {
        $url = getCurUrl();

        $this->assign('uri', $url);

        echo $this->twig->render($template.'.html', $this->data);
    }

    /**
     * 顶层跳转
     * @param $url
     * @param $mess
     */
    protected function topsuccess($url, $mess) {
        echo "<script>";
        echo "alert('{$mess}');";

        if(!empty($url)) {
            echo "top.location.href='{$url}';";
        }
        echo "</script>";
    }

    /**
     * 成功跳转
     * @param $url
     * @param $mess
     */
    protected function success($url, $mess) {
        echo "<script>";
        echo "alert('{$mess}');";

        if(!empty($url)) {
            echo "location.href='{$url}';";
        }

        echo "</script>";
    }

    /**
     * 失败跳转
     * @param $url
     * @param $mess
     */
    protected function error($url, $mess) {
        echo "<script>";
        echo "alert('ERROR:{$mess}');";

        if(!empty($url)) {
            echo "location.href='{$url}';";
        }

        echo "</script>";
    }
}
